package com.yibo.yunpicture.infrastructure.manager.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yibo.yunpicture.infrastructure.api.CosManager;
import com.yibo.yunpicture.infrastructure.config.CosClientConfig;
import com.yibo.yunpicture.infrastructure.exception.BusinessException;
import com.yibo.yunpicture.infrastructure.exception.ErrorCode;
import com.yibo.yunpicture.infrastructure.exception.ThrowUtils;
import com.yibo.yunpicture.infrastructure.manager.upload.modal.dto.file.UploadPictureDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

@Component
@Slf4j
public class FileManager {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    public COSClient cosClient;

    @Resource
    private CosManager cosManager;

    /**
     * 通过文件上传图片
     *
     * @param multipartFile
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureDTO uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        //校验图片
        vaildPicture(multipartFile);
        //图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originFileName = multipartFile.getOriginalFilename();
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originFileName));
        String uploadFilePath = String.format("%s/%s", uploadPathPrefix, uploadFileName);
        File file = null;
        try {
            //创建临时文件
            file = File.createTempFile(uploadFilePath, null);
            multipartFile.transferTo(file);
            //上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //封装返回结果
            UploadPictureDTO uploadPictureDTO = new UploadPictureDTO();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureDTO.setPicName(FileUtil.mainName(originFileName));
            uploadPictureDTO.setPicSize(FileUtil.size(file));
            uploadPictureDTO.setPicWidth(picWidth);
            uploadPictureDTO.setPicHeight(picHeight);
            uploadPictureDTO.setPicScale(picScale);
            uploadPictureDTO.setPicFormat(imageInfo.getFormat());
            uploadPictureDTO.setUrl(cosClientConfig.getHost() + "/" + uploadFilePath);
            return uploadPictureDTO;
        } catch (IOException e) {
            log.error("图片上传到对象存储失败", e);
            throw new RuntimeException(e);
        } finally {
            this.deleteTempFile(file);
        }
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     */
    private void vaildPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile.isEmpty(), ErrorCode.PARAMS_ERROR, "文件不能为空");
        //1. 校验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > ONE_M * 2, ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
        //2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("png", "jpg", "jpeg", "gif", "bmp", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }

    /**
     * 通过URL上传图片
     *
     * @param fileUrl
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureDTO uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        //校验图片
        vaildPictureByUrl(fileUrl);
        //图片上传地址
        String uuid = RandomUtil.randomString(16);
        //String originFileName = multipartFile.getOriginalFilename();
        String originFileName = FileUtil.mainName(fileUrl);
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originFileName));
        String uploadFilePath = String.format("%s/%s", uploadPathPrefix, uploadFileName);
        File file = null;
        try {
            //创建临时文件
            file = File.createTempFile(uploadFilePath, null);
            //multipartFile.transferTo(file);
            HttpUtil.downloadFile(fileUrl, file);
            //上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //封装返回结果
            UploadPictureDTO uploadPictureDTO = new UploadPictureDTO();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureDTO.setPicName(FileUtil.mainName(originFileName));
            uploadPictureDTO.setPicSize(FileUtil.size(file));
            uploadPictureDTO.setPicWidth(picWidth);
            uploadPictureDTO.setPicHeight(picHeight);
            uploadPictureDTO.setPicScale(picScale);
            uploadPictureDTO.setPicFormat(imageInfo.getFormat());
            uploadPictureDTO.setUrl(cosClientConfig.getHost() + "/" + uploadFilePath);
            return uploadPictureDTO;
        } catch (IOException e) {
            log.error("图片上传到对象存储失败", e);
            throw new RuntimeException(e);
        } finally {
            this.deleteTempFile(file);
        }
    }

    /**
     * 校验URL
     *
     * @param fileUrl
     */
    private void vaildPictureByUrl(String fileUrl) {
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址为空");
        // 1. 验证 URL 格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }

        // 2. 校验 URL 协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 3.发送 HEAD 请求已验证文件是否存在
        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            // 未正常返回，无需执行其他判断
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 4. 校验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误，仅支持 JPEG、JPG、PNG、WEBP 格式的图片");
                // 5. 校验文件大小
                String contentLengthStr = response.header("Content-Length");
                if (StrUtil.isNotBlank(contentLengthStr)) {
                    try {
                        long contentLength = Long.parseLong(contentLengthStr);
                        final long TWO_MB = 2 * 1024 * 1024; //限制文件大小为 2MB
                        ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2MB");
                    } catch (NumberFormatException e) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                    }
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    private void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        //删除临时文件
        boolean deleteDTO = file.delete();
        if (!deleteDTO) {
            log.error("file delete error , filePath={}", file.getAbsolutePath());
        }
    }
}
